export default {
  namespaced: true,
  state: () => ({
    cart: JSON.parse(localStorage.getItem('cart') || '[]')
  }),
  mutations: {
    addTOCart(state, goods) {
      const findResult = state.cart.find((x) => x.goods_id === goods.goods_id);
      if (!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      this.commit('m_cart/saveToStorage')
    },
    //更新购物车中商品的勾选状态
    updateGoodsState(state, goods) {
      //查找
      const findResult = state.cart.find((x) => x.goods_id === goods.id);
      // console.log(findResult)
      if (findResult) {
        findResult.goods_state = goods.state
        this.commit('m_cart/saveToStorage')
      }
    },
    //更新购物车中商品的数量
    updateGoodsCount(state, goods) {
      const findResult = state.cart.find((x) => x.goods_id === goods.id);
      if (findResult) {
        findResult.goods_count = goods.goods_count
        this.commit('m_cart/saveToStorage')
      }
    },
    saveToStorage(state) {
      // console.log(state.cart)
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    updateAllGoodsState(state,newState){
      state.cart.forEach(x=>x.goods_state = newState)
      this.commit('m_cart/saveToStorage')
    }

  },
  actions: {},
  getters: {
    total(state) {//购物车数量(包括未选择的)
      return state.cart.reduce((amt, item) => amt += item.goods_count, 0)
    },
    // 勾选的商品的总数量
    checkedCount(state) {
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
    },
    checkedGoodsAmount(state) {
      // console.log(state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price, 0).toFixed(2))
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price, 0).toFixed(2)
    }
  }
}
